package com.teamb6.shop.controller.front;


import com.teamb6.shop.domain.*;
import com.teamb6.shop.service.*;
import com.teamb6.shop.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
public class OrderController {

    /*@Value("#{addressService}")*/
    @Autowired
    private AddressService addressService;

    @Autowired
    private ShopCartService shopCartService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private IndentService indentService;

    @Autowired
    private ActivityService activityService;

    @RequestMapping("/order")
    public String showOrder(HttpSession session, Model model) {

        User user = (User) session.getAttribute("user");
//        User user = new User();
//        user.setUserid(7);
        if (user == null) {
            return "redirect:/users/login";
        }

        //查询当前用户的默认收货地址
        AddressExample addressExample = new AddressExample();
        addressExample.or().andUseridEqualTo(user.getUserid()).andStatusEqualTo(1);
        List<Address> addressList = addressService.getAllAddressByExample(addressExample);

        model.addAttribute("addressList", addressList);

        //订单信息
        //获取当前用户的购物车信息
        ShopCartExample shopCartExample = new ShopCartExample();
        shopCartExample.or().andUseridEqualTo(user.getUserid());
        List<ShopCart> shopCart = shopCartService.selectByExample(shopCartExample);

        //获取购物车中的商品信息
        List<Goods> goodsAndImage = new ArrayList<>();

        Float totalPrice = new Float(0);
        Float goodsPrice = new Float(0);
        Integer oldTotalPrice = 0;

        for (ShopCart cart : shopCart) {
            //分别从购物车列表中获取每个商品
            Goods goods = goodsService.selectById(cart.getGoodsid());

            List<ImagePath> imagePathList = goodsService.findImagePath(goods.getGoodsid());
            goods.setImagePaths(imagePathList);
            goods.setNum(cart.getGoodsnum());

            //活动信息
            Activity activity = activityService.selectByKey(goods.getActivityid());
            goods.setActivity(activity);

            //处理折扣信息
            //如果商品折扣不为1
            if (activity.getDiscount() != 10) {
                goodsPrice = goods.getPrice() * goods.getNum() * activity.getDiscount()/10;
            }else{
                goodsPrice = (float)goods.getPrice() * goods.getNum();
            }

            if ((activity.getFullnum() != null && activity.getFullnum()!=0) && goods.getNum() >= activity.getFullnum()) {
                if(activity.getDiscount() != 10){
                    goodsPrice -= (float) (activity.getDiscount()/10 * goods.getPrice() * (goods.getNum() - activity.getReducenum()));
                }else{
                    goodsPrice -= (float) (goods.getPrice() * (goods.getNum() - activity.getReducenum()));
                }
            }

            if ((activity.getFullprice() != null && activity.getFullprice()!=0) && goodsPrice > activity.getFullprice()) {
                goodsPrice -= activity.getReduceprice();

            }
            totalPrice = totalPrice + goodsPrice;
            oldTotalPrice = oldTotalPrice + goods.getNum() * goods.getPrice();
            goods.setNewPrice(goodsPrice);
            goodsAndImage.add(goods);
        }

        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("oldTotalPrice", oldTotalPrice);
        model.addAttribute("goodsAndImage", goodsAndImage);

        return "checkout_billing";
    }

    @RequestMapping("/orderFinish")
    @ResponseBody
    public Msg orderFinish(Float oldPrice, Float newPrice, Boolean isPay, Integer addressid, HttpSession session) {
        User user = (User) session.getAttribute("user");
//        User user = new User();
//        user.setUserid(7);

        //获取订单信息
        ShopCartExample shopCartExample = new ShopCartExample();
        shopCartExample.or().andUseridEqualTo(user.getUserid());
        List<ShopCart> shopCart = shopCartService.selectByExample(shopCartExample);

        //删除购物车
        for (ShopCart cart : shopCart) {
            shopCartService.deleteByKey(new ShopCartKey(cart.getUserid(), cart.getGoodsid()));
        }

        //把订单信息写入数据库
        Indent order = new Indent(null, user.getUserid(), new Date(), oldPrice, newPrice, isPay, false, false, false, addressid, null, null);
        indentService.insertIndent(order);
        //插入的订单号
        Integer orderId = order.getOrderid();

        //把订单项写入orderitem表中
        for (ShopCart cart : shopCart) {
            indentService.insertOrderItem(new OrderItem(null, orderId, cart.getGoodsid(), cart.getGoodsnum()));
        }

        return Msg.success("购买成功").add("orderid",orderId);
    }

    @RequestMapping(value = "/checkout/{orderid}/{newprice}")
    public String orderFinish(@PathVariable("orderid")Integer orderid,@PathVariable("newprice")Float newprice,HttpSession session,Model model) {
        HttpCookie cookie = new HttpCookie("orderid",orderid.toString());

        model.addAttribute("orderId",orderid);
        session.setAttribute("orderId",orderid);
        session.setAttribute("newprice",newprice);
        model.addAttribute("newprice",newprice);
        return "checkout_payment";
    }



    @RequestMapping(value = "/deleteOrder/{orderid}", method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteOrder(@PathVariable("orderid")Integer orderid, HttpSession session) {
        User user = (User) session.getAttribute("user");
//        User user = new User();
//        user.setUserid(1);
        if(user == null) {
            return Msg.fail("请先登录");
        }

        indentService.delectOrderItemByOrderid(orderid);
        indentService.delectIndentById(orderid);
        return Msg.success("取消成功");
    }

//    @RequestMapping(value = "/payorder")
//    @ResponseBody
//    public String payOrder(Integer orderid, HttpSession session) {
//        User user = (User) session.getAttribute("user");
////        User user = new User();
////        user.setUserid(1);
//        if(user == null) {
//            return "/main";
//        }
//
//        //获取订单中的具体商品
//        OrderItemExample orderItemExample = new OrderItemExample();
//        orderItemExample.or().andOrderidEqualTo(orderid);
//        List<OrderItem> orderItems = indentService.getOrderItemByExample(orderItemExample);
//
//        //销量+1
//        Goods goods = new Goods();
//        for(OrderItem orderItem : orderItems){
//            goods = goodsService.selectById(orderItem.getGoodsid());
//            goods.setSales(goods.getSales()+1);
//            goodsService.updateGoods(goods);
//        }
//
//        //修改为已支付
//        Indent indent = indentService.selectByPrimaryKey(orderid);
//        indent.setIspay(true);
//        indentService.updateIndentByKey(indent);
//
//        return "/main";
//    }



}
